<template>
  <div id="index">
    <div class="mod-config" id="adminList">
      <el-form id="admninFrom" :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
          <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
          <el-button type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除
          </el-button>
          <el-button type="success" @click="download()">模板下载</el-button>
          <el-button type="warning" @click="importBook()">模板导入</el-button>
        </el-form-item>
      </el-form>
      <el-table id="table" :data="dataList" border v-loading="dataListLoading"
        @selection-change="selectionChangeHandle">
        <el-table-column type="selection" header-align="center" align="center" width="50">
        </el-table-column>
        <el-table-column prop="id" header-align="center" align="center" label="id">
        </el-table-column>
        <el-table-column prop="instrumentName" header-align="center" align="center" label="仪器名称">
        </el-table-column>
        <el-table-column prop="instrumentNumber" header-align="center" align="center" label="仪器编号">
        </el-table-column>
        <el-table-column prop="accuracyRating" header-align="center" align="center" label="准确度">
        </el-table-column>
        <el-table-column prop="measuringRange" header-align="center" align="center" label="量程">
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination id="page" @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
        :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
      <el-dialog customClass="customWidth" :modal="true" :visible.sync="ImportdialogVisible" :title="ImportTitle"
        width="400px">
        <el-form :model="form">
          <el-form-item>
            <el-upload class="upload-file" drag ref="uploadExcel" :action="url" :limit=limitNum :auto-upload="false"
              accept=".xlsx" :before-upload="beforeUploadFile" :on-change="fileChange" :on-exceed="exceedFile"
              :on-success="handleSuccess" :on-error="handleError" :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击选择Excel文件</em></div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <div style="float: right">
              <el-button @click="ImportdialogVisible = false" size="small">取 消</el-button>
              <el-button size="small" type="primary" @click="submitUpload()">立即导入</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AddOrUpdate from './instrument-add-or-update'
import { httpBaseUrl } from "@/util/globa";

export default {
  data() {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      /* --- 以下导入Excel文件对话框绑定的数据 --- */
      ImportdialogVisible: false, //"导入"对话框是否可见
      ImportTitle: '导入Excel', //"导入"对话框的标题
      limitNum: 1,//导入文件的个数
      form: {    //"导入"表单绑定file，并初始化
        file: ''
      },
      fileList: [],//"导入"文件列表
      url: httpBaseUrl + "/reportapproval/instrument/uploadFile"
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList()
  },
  methods: {
    download() {
      // 后端提供的下载地址
      const fileUrl = httpBaseUrl + '/static/在用仪器一览表模板.xlsx';

      // 创建一个 <a> 标签
      const a = document.createElement('a');
      a.href = fileUrl;
      a.download = '模板.xlsx';  // 设置默认下载的文件名

      // 模拟点击下载
      a.click();
    },

    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/reportapproval/instrument/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'key': this.dataForm.key
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    }
    ,
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    }
    ,
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    }
    ,
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    }
    ,
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    }
    ,
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/reportapproval/instrument/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then((data) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    importBook() { //弹出导入对话框
      let self = this;
      self.ImportdialogVisible = true;
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });

    },
    // 文件状态改变时的钩子
    fileChange(file) {
      this.form.file = file.raw
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      // let extension = file.name.substring(file.name.lastIndexOf('.')+1); //获取上传文件的扩展名
      // console.log("文件扩展名为:"+extension);
      let size = file.size / 1024 / 1024; //设置上传文件的大小
      const isXLSX = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase() === 'xlsx';
      if (!isXLSX) {
        this.$notify.warning({
          title: '警告',
          message: `只能上传Excel（即后缀是.xlsx）的文件`
        });
      }
      if (size > 10) {
        this.$notify.warning({
          title: '警告',
          message: `文件大小不得超过10M`
        });
      }
    },

    // 文件上传成功时的钩子
    handleSuccess() {
      let self = this;
      this.$notify.success({
        title: '成功',
        message: `文件导入成功`
      });
      self.ImportdialogVisible = false;
      this.getDataList()
      this.fileList = []
    }
    ,
    // 文件上传失败时的钩子
    handleError() {
      this.$notify.error({
        title: '错误',
        message: `文件导入失败`
      });
      this.fileList = []
    }
    ,

    submitUpload() {
      let self = this;
      if (self.form.file == '') {
        this.$notify.error({
          title: '错误',
          message: `请选择要导入的文件`
        });
        return;
      }
      self.$refs.uploadExcel.submit();
    }
    ,
  }
}
</script>
<style scoped>
.el-dialog {
  max-width: 600px;
}

.el-upload {
  margin-bottom: 20px;
}
</style>
